<template>
	<view class="" :style="[AppSkinVar]">
		<e-loading-page :loading="loading || payLoading">
			<template #icon>
				<loader></loader>
			</template>
		</e-loading-page>

		<view class="preview-proxy-order e-rela">
			<view class="preview-proxy-order__bg"></view>
			<view class="preview-proxy-order__box">
				<view class="e-flex-y-center e-p-l-40 preview-proxy-order__top c-white">
					<image :src="$fullLink(orderInfoVo.orderUserPhoto)" class="img-80" v-if="orderInfoVo.orderUserPhoto"
						mode=""></image>
					<text class="e-p-l-28 e-font-34 w-600 e-m-r-8">{{orderInfoVo.orderUserNickname || ''}}</text>
					<text class="e-font-26">的代付邀请</text>
				</view>
				<view class="e-p-l-20 e-p-r-20">
					<view class="preview-proxy-order__content border-radius-20 bg-white">
						<view class="e-m-b-26 e-flex-y-center">
							<text class="c-333 e-font-28 w-600 e-p-r-10">剩余支付时间</text>
							<view class="preview-proxy-order__countdown e-flex-xy-center">
								<text class="c-white e-font-22">{{hours}}</text>
							</view>
							<text class="e-p-l-6 e-p-r-6">:</text>
							<view class="preview-proxy-order__countdown e-flex-xy-center">
								<text class="c-white e-font-22">{{minute}}</text>
							</view>
							<text class="e-p-l-6 e-p-r-6">:</text>
							<view class="preview-proxy-order__countdown e-flex-xy-center">
								<text class="c-white e-font-22">{{seconds}}</text>
							</view>
						</view>
						<view class="preview-proxy-order__line e-m-b-28">

						</view>
						<view class="e-font-24 e-m-b-14" style="color: #9C9C9C;">
							代付金额
						</view>
						<view class="e-flex-y-center e-font-36 w-600 c-red">
							<text>{{$unitEn}}</text>
							<text class="e-font-50">{{info.money}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="e-p-20">
			<view class="custom-order-list" v-for="(item, index) in orderVos" :key="index">
				<PreviewOrderGoodsItem :store="item" :goodsList="item.canList" :noCanList="item.noCanList"
					:exceedLimitList="item.exceedLimitList" @showReason="handleShowReason" class="e-m-b-20">
					<template #header>
						<view class="e-m-b-20">代付订单信息</view>
					</template>
					<template #storeCoupon
						v-if="item.params && item.params.coupon && item.params.coupon.couponList.length">
						<view class="e-flex-xy-center e-flex-between e-font-28 c-666 e-p-l-20"
							@tap="handleOpenCoupon(2, item.storeId)">
							<text>{{ $t('classify.店铺优惠') }}</text>
							<view class="e-flex-1 text-right c-red">-{{ item.orderMoneyCoupon }}</view>
							<app-image src="arrow_right.png" :size="['36rpx']" />
						</view>
					</template>
					<template #orderVos>
						<view class="" v-if="[3, 5].includes(receivingType) && item.canList && item.canList.length">
							<DeliveryTime :key="deliveryTimeKey" :orderVos="item" v-if="item.fig"
								:orderDeliveryfee="item.orderDeliveryfee" @setDeliveryTime="setDeliveryTime"
								:receivingType="receivingType" :deliveryTimes="deliveryTimes"></DeliveryTime>
						</view>
						<view class="" v-if="receivingType === 2 && item.canList && item.canList.length">
							<StoreAddressSelect v-if="receivingIds && receivingIds.length" :receivingIds="receivingIds"
								:storeId="item.storeId" @setPredictTime="setPredictTime"
								@updateReceivingIds="updateReceivingIds"></StoreAddressSelect>
						</view>
					</template>
				</PreviewOrderGoodsItem>
			</view>


			<view class="" v-show="deductionList.length || giveList.length">
				<view class="e-flex e-m-t-20 e-p-t-24 e-p-b-24 e-p-l-30 bg-white">
					{{ $t('nearby.deduction') }}
				</view>
				<view class="bg-white">
					<view class="preview-order-mode" v-for="item in deductionList" :key="item.strategy">
						<view class="preview-order-mode__mask" @tap="handleTapDeductionItem(item, 1)"></view>
						<view class="e-flex e-p-b-20">
							<view class="e-m-r-10">
								<load-image size="32rpx" :src="item.icon"></load-image>
							</view>
							<text class="e-font-24 c-regular">{{ item.name }}</text>
							<text class="e-font-24 c-regular">积分抵扣</text>
						</view>
						<e-line color="#E6E6E6"></e-line>
						<view class="e-flex e-flex-between e-p-t-20">
							<text class="fw-600">{{ $unitEn }}{{ item.payMoney }} +
								{{ item.deductMoney }}{{ item.name }}</text>
							<view class="e-flex">
								<radio :disabled="!item.deductMoney" :color="AppSkin.primary"
									:value="`${item.strategy}`" :checked="item.check"
									@tap.stop="handleTapDeductionItem(item, 1)" />
							</view>
						</view>
					</view>
					<template v-if="giveList.length">
						<view class="preview-order-mode" v-for="item in [giveList[0]]" :key="item.strategy">
							<view class="preview-order-mode__mask" @tap="handleTapDeductionItem(item, 2)"></view>
							<view class="e-flex e-p-b-20">
								<view class="e-m-r-10">
									<image src="/pages/systemPay/static/nearby/icon.png" class="img-32 e-m-r-10">
									</image>
								</view>

								<text class="e-font-24 c-regular">原价购买</text>
							</view>
							<e-line color="#E6E6E6"></e-line>
							<view class="e-flex e-flex-between e-p-t-20">
								<text class="fw-600">{{ $unitEn }}{{ item.payMoney }}</text>
								<view class="e-flex">
									<radio :color="AppSkin.primary" :value="`${item.strategy}`"
										:checked="!deductionModeId.length"
										@tap.stop="handleTapDeductionItem(item, 2)" />
								</view>
							</view>
						</view>
					</template>
				</view>
			</view>
			<view class="bg-white border-radius-20 overflow-hidd">
				<view class="e-p-l-20 e-p-r-20 e-p-t-25 e-p-b-25">
					<text class="fw-600">{{ $t('nearby.支付方式') }}</text>
				</view>
				<pay-list ref="payListRef" :isTrace="!!isTrace" :isDefault="isTrace ? 'N' : 'Y'"
					:proIds="proIds"></pay-list>
			</view>
		</view>


		<password-popup ref="passwordPopupRef" :payMoney="info.payMoney" :show="show" @close="show = false"
			@confirm="passwordPay"></password-popup>

		<view style="height: 140rpx"></view>
		<view class="fixed-button e-flex e-flex-between bg-white">
			<view class="e-flex e-flex-between">
				<text class="e-font-30">{{ $t('cart.总计') }}：</text>
				<text class="c-red e-font-36">{{ $unitEn }}{{ info.payMoney }}</text>
			</view>
			<button class="bg-primary c-white" @tap="buy(true)">{{ $t('classify.去支付') }}</button>
		</view>
		<!-- 账户选择弹窗 -->
		<DiscountPop v-model:show="discountPopShow" :deductionType="deductionType"
			v-model:deductionStrategy="deductionStrategy" :selectedCommodityUrl="selectedCommodityUrl"
			:deductionMode="deductionMode" :deputyMoneyDeduction="deputyMoneyDeduction" @submit="handleChangeSelect">
		</DiscountPop>

		<!-- 优惠券详情 -->
		<CouponPop v-model:value="showCouponPop" v-model:couponList="couponList" :isPlat="isPlat"
			@changeCouponStatus="changeCouponStatus" @closeUse="closeUse"></CouponPop>

		<!-- 不可下单原因 -->
		<NoCanReason v-model:value="showReason" :noCanList="noCanList" :exceedLimitList="exceedLimitList"
			:receivingType="receivingType"></NoCanReason>

		<!-- 提示添加收货地址 -->
		<e-modal :show="showAddrPop" :confirmText="$t('classify.去添加')" @confirm="handleJumpAddress" @cancel="$back()">
			<view class="slot-content">
				{{ $t('classify.请先添加收货地址') }}
			</view>
		</e-modal>
		<card-valid-code-popup :show="cardValidCodePopupShow" :payMoney="info.payMoney" @cancel="handleCancelCardPay"
			@confirm="handleCardPay"></card-valid-code-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, watch } from 'vue';
	import { debounce, throttle } from '@/common/utils';
	import {
		postPreviewOneGoodsOrder,
		postPurchaseOneGoods,
		postPreviewCartGoodsOrder,
		postPurchaseCartGoods,
		postAgainCreateGoods,
		postAgainPurchaseGoods,
		getPayResult,
		getOrderQueryActivity,
		getAddressList,
		getDeliveryPlaceList,
		receiveSecurities,
		getCouponByShare,

		behalfPaymentPre,
		activityV2,
		behalfPayment
	} from '@/common/request/api';
	import type {
		PurchaseGoodsParams,
		PreviewOrderData,
		AddressItem,
		OrderCouponsItem,
		OrderGoods,
		DeliveryPlace,
		PurchaseGoodsPayData,
		DeductionStrategy,
		deductionAccountItem
	} from '@/common/request/api';
	import { useCurrentInstance, useLocation } from '@/common/hooks';
	import DiscountPop from './child/discount/index.vue';
	import CouponPop from './child/coupon';
	import DeliveryTabs from './child/deliveryTabs.vue';
	import DeliveryTime from './child/deliveryTime.vue';
	import StoreAddressSelect from './child/store-address.vue';
	import NoCanReason from './child/noCanReason.vue';
	import PreviewOrderGoodsItem from './child/goodsItem.vue';
	import CardValidCodePopup from '../child/cardValidCodePopup.vue';
	import { useUser, useShoppingCart } from '@/common/stores';
	import { storeToRefs } from 'pinia';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import type { Mutable } from '@/typings/utils';
	import type { UniGlobalData } from '@/typings/uni';
	import { usePay } from '../hooks/usePay';
	import type { PayListInstance, PasswordPopupInstance } from '@/typings/components';
	import { PayType } from '@/env';

	const props = defineProps({
		type: {
			type: String,
			required: true
		}, //下单类型 1单商品 2购物车 3多商品或订单重购买
		qty: String, //单商品下单参数
		skuId: String, //单商品下单参数
		basketIds: String, //购物车下单参数
		buys: String, //多商品下单参数
		isTrace: String, // 是否来自视频带货
		receivingType: String,
		aId: String
	});

	const ctx = useCurrentInstance();

	const { payLoading, systemPay, cardValidCodePopupShow, checkCardPay, handleCancelCardPay, handleCardPay, getH5PayResult } = usePay();

	const pageParams : Partial<Mutable<typeof props>> = { ...props };
	delete pageParams.isTrace;
	delete pageParams.aId;
	delete pageParams.type;

	const { getCart } = useShoppingCart();
	const { userInfo } = storeToRefs(useUser());

	const { latitude, longitude, getUserLocation } = useLocation();

	const loading = ref(true);

	const orderInfoVo = ref({});
	const hours = ref();
	const minute = ref();
	const seconds = ref();
	const timer = ref();

	const countDown = () => {
		timer.value = setTimeout(() => {
			const endTime = new Date(orderInfoVo.value.invalidTime)
			const nowTime = new Date().getTime()
			if (nowTime > endTime) {
				hours.value = '00'
				minute.value = '00'
				seconds.value = '00'
				hanldeClearTimeout()
				return
			}
			let __surplus = endTime - nowTime
			if (__surplus < 0) {
				__surplus = 0
			}
			const result = parseInt(__surplus / 1000)
			hours.value = Math.floor(result / 3600 % 24);
			hours.value = hours.value >= 10 ? hours.value : '0' + hours.value
			minute.value = Math.floor(result / 60 % 60);
			minute.value = minute.value >= 10 ? minute.value : '0' + minute.value
			seconds.value = Math.floor(result % 60);
			seconds.value = seconds.value >= 10 ? seconds.value : '0' + seconds.value
			countDown()
		}, 1000)
	}
	const hanldeClearTimeout = () => {
		clearTimeout(timer.value)
		timer.value = null
	}

	// receivingType 商品发货类型：2-快递 3-闪送 4-核销 5-自提 6-配送 pre接口
	// receivingType 订单收货方式 ：1快递 2自提 3-闪送 4-核销 5-配送 pay接口
	const receivingType = ref(1);
	if (props.receivingType) {
		switch (props.receivingType) {
			case '2':
				receivingType.value = 1;
				break;
			case '3':
				receivingType.value = 3;
				break;
			case '4':
				receivingType.value = 4;
				break;
			case '5':
				receivingType.value = 2;
				break;
			case '6':
				receivingType.value = 5;
				break;
		}
	} else {
		receivingType.value = 1;
	}

	const info = ref<PreviewOrderData>({
		orderVos: [],
		storeReceiving: false,
		money: 0,
		moneyDis: 0,
		payMoney: 0,
		freight: 0,
		deliveryfee: 0,
		moneyDeduction: 0,
		couponMoney: 0,
		couponMoneySys: 0,
		deliveryModes: [],
		delivery: false
	});
	const getCanList = (item : OrderGoods) =>
		item.deputys.filter((items) => {
			// isFlash 0 不可以下单 1可以
			if (receivingType.value === 3 && items.isFlash) {
				if (!items.flashDeliveryLimit || (items.flashDeliveryLimit && items.commodityCount <= items.flashDeliveryLimit)) {
					return items;
				}
			} else if (items.isFlash) {
				return items;
			}
		});

	const orderVos = computed(() => {
		return info.value.orderVos.map((item) => {
			return {
				...item,
				// isFlash 0 不可以下单 1可以
				canList: getCanList(item),
				noCanList: item.deputys.filter((item) => !item.isFlash),
				// 超出闪送数量
				exceedLimitList:
					receivingType.value === 3
						? item.deputys.filter((deputy) => {
							return deputy.isFlash && deputy.flashDeliveryLimit && deputy.commodityCount > deputy.flashDeliveryLimit;
						})
						: []
			};
		});
	});

	// 虚拟商品联系方式
	const contactPhone = ref(userInfo.value.phone || '');
	let preQueryData = ''; //预览订单数据
	const couponShareCode = ref(''); //优惠券码
	let isFirstCouponShare = false; //是否首次领取券码
	let couponShareId = ''; //优惠券码获取的优惠券id
	const couponId = ref(''); //当前选中的优惠券

	watch(couponShareCode, () => {
		handleReceivingCoupon();
	});

	const showCouponPop = ref(false); // 优惠券弹窗

	const address = ref<AddressItem | undefined>(undefined);
	const handleSelectAddress = (e : AddressItem) => {
		address.value = e;
	};

	const showAddrPop = ref(false);
	const handleJumpAddress = () => {
		ctx.$goTo(
			'/pages/user/receivingAddress/index',
			{ type: 1 },
			{
				selectAddress: handleSelectAddress
			}
		);
		showAddrPop.value = false;
	};

	const show = ref(false);

	const storeId = ref(''); // 当前操作的店铺
	const storeAddress = ref<DeliveryPlace | undefined>(undefined);

	watch(address, (newValue) => {
		if (newValue?.id && !loading.value) {
			getData();
		}
	});

	const discountPopShow = ref(false); // 抵扣弹窗
	const deductionStrategy = ref<DeductionStrategy[]>([]);
	const deductionOpen = ref('N'); // 是否开启抵扣 N 关闭 Y 开启
	const deductionMode = ref('N'); // 抵扣模式 是否足额抵扣 N 不足额抵扣 Y 足额抵扣
	const deductionType = ref('N'); // 抵扣方式 N 单账户 Y 多账户

	const selectedCommodityUrl = ref(''); // 当前选中的商品图片

	let selectDeductionStrategy : Record<string, string> = {}; // 当前选中的抵扣
	const getDeductionStrategy = () => (Object.keys(selectDeductionStrategy).length ? JSON.stringify(selectDeductionStrategy) : undefined);

	const deputyMoneyDeduction = ref<number | null>(null); // 当前操作项抵扣额
	const commoditySpecId = ref(''); // 当前选中的规格id

	const paltFormCoupon = ref<OrderCouponsItem[]>([]); // 平台优惠券详情
	const showCoupon = ref(false);
	const isPlat = ref(false); // 是否平台优惠
	const couponList = ref<OrderCouponsItem[]>([]);

	const deliveryTabList = ref<
		{
			name : string;
			value : number;
		}[]
	>([]);

	// 不支持下单的商品列表
	const noCanList = ref<OrderGoods['deputys']>([]);
	//超出闪送数量限制的商品列表
	const exceedLimitList = ref<OrderGoods['deputys']>([]);
	const showReason = ref(false);

	const deliveryTimes = ref<
		Array<{
			selectTime : string;
			deliveryTimes : string;
			storeId : string;
		}>
	>([]); // 配送时间
	const remarks = ref<Record<string, string>>({}); // 订单备注

	const receivingIds = ref<
		Array<{
			predictTime ?: string;
			storeId : string;
			storeAddress : DeliveryPlace;
		}>
	>([]);

	// 是否虚拟商品 虚拟商品不能加入购物车
	const isVirtualGoods = ref(false);
	const deliveryTimeKey = 'deliveryTimeKey'; //用于切换tab的时候初始化

	const proIds = ref('');

	watch(
		remarks,
		(val) => {
			if (val) {
				uni.setStorageSync('orderRemarks', val);
			}
		},
		{
			immediate: true,
			deep: true
		}
	);

	const handleReceivingCoupon = debounce(async function () {
		// 优惠券码
		if (couponShareCode.value.length === 16 && !isFirstCouponShare) {
			// 优惠券码 如果存在优惠券码，先领券,再通过券码获取优惠券id，这个优惠券id要和平台券和商家券一起传给后端
			try {
				await receiveSecurities(couponShareCode.value);
			} catch (e) {
				uni.removeStorageSync('couponShare');
				couponShareCode.value = '';
			}

			try {
				const result = await getCouponByShare({ couponShareCode: couponShareCode.value });
				if (result.data) {
					couponShareId = result.data;
				}
			} catch (e) {
				//TODO handle the exception
			}
			handleGetQueryOrderData();
		} else {
			couponShareId = '';
			handleGetQueryOrderData();
		}
	}, 500);
	const handleChangeReceivingType = () => {
		deliveryTimes.value = [];
		getData();
	};
	const setDeliveryTime = (val : (typeof deliveryTimes)['value'][0]) => {
		// 设置配送时间
		// 筛选掉不在订单内的店铺
		const orderStoreIds = info.value.orderVos.map((item) => item.storeId);
		const deliveryTime = deliveryTimes.value.filter((item) => orderStoreIds.includes(item.storeId));
		const index = deliveryTime.findIndex((item) => item.storeId === val.storeId);
		if (index >= 0) {
			deliveryTime.some((item) => {
				if (item.storeId === val.storeId) {
					item.selectTime = val.selectTime;
					item.deliveryTimes = val.deliveryTimes;
					return true;
				}
			});
		} else {
			deliveryTime.push(val);
		}
		deliveryTimes.value = deliveryTime;
		uni.setStorageSync('deliveryTimes', deliveryTime);
	};
	const setPredictTime = (predictTime : string, _storeId : string) => {
		receivingIds.value?.some((item) => {
			if (item.storeId === _storeId) {
				item.predictTime = predictTime;
				return true;
			}
		});
		uni.setStorageSync('receivingIds', receivingIds.value);
	};
	const updateReceivingIds = (_storeAddress : DeliveryPlace) => {
		if (receivingIds.value && receivingIds.value.length) {
			receivingIds.value.some((item, index) => {
				if (item.storeId === _storeAddress.storeId) {
					receivingIds.value[index].storeAddress = _storeAddress;
				}
			});
		}
	};
	const handleShowReason = (list : OrderGoods['deputys'], list1 : OrderGoods['deputys']) => {
		showReason.value = true;
		noCanList.value = list;
		exceedLimitList.value = list1;
	};
	const closeUse = () => {
		if (isPlat.value) {
			paltFormCoupon.value.forEach((item) => (item.check = false));
		} else {
			const index = info.value.orderVos.findIndex((item) => item.storeId === storeId.value);
			if (index > -1) {
				const item = { ...info.value.orderVos[index] };
				item.params?.coupon?.couponList.forEach((item) => (item.check = false));
				info.value.orderVos.splice(index, 1, item);
			}
		}
	};
	const handleOpenCoupon = (type : number, _storeId ?: string) => {
		storeId.value = _storeId || '';
		if (type === 1) {
			couponList.value = paltFormCoupon.value;
			isPlat.value = true;
		} else {
			isPlat.value = false;
			info.value.orderVos.some((item) => {
				if (item.storeId === _storeId) {
					couponList.value = item.params?.coupon?.couponList || [];
				}
			});
		}
		showCouponPop.value = true;
	};
	const deductionModeId = ref<string[]>([]); //选中的抵扣账户
	const deductionList = ref<deductionAccountItem[]>([]);
	const giveList = ref<deductionAccountItem[]>([]);
	const giveModeId = ref<string[]>([]); //选中的抵扣账户
	const hasOriginal = ref(false);
	const handleTapDeductionItem = (items : deductionAccountItem, type : number) => {
		if (type === 1) {
			if (items.deductMoney) {
				hasOriginal.value = false;
				if (deductionType.value === 'N') {
					deductionModeId.value = [items.strategy];
				} else {
					if (deductionModeId.value.includes(items.strategy)) {
						deductionModeId.value.splice(
							deductionModeId.value.findIndex((item) => item === items.strategy),
							1
						);
					} else {
						deductionModeId.value.push(items.strategy);
					}
				}
			}
			console.log(deductionModeId.value);
		} else {
			deductionModeId.value = [];
			giveModeId.value = [items.strategy];
		}

		handleGetQueryOrderData();
	};

	const getGiveStrategy = () => {
		let obj = {};
		const deductionStrategy = deductionModeId.value.join(',');
		info.value.orderVos.forEach((vos) => {
			vos.deputys.forEach((deputy) => {
				obj[deputy.commoditySpecId] = deductionStrategy;
			});
		});
		return {
			deductionStrategy: Object.keys(obj).length ? JSON.stringify(obj) : undefined,
			giveStrategy: giveModeId.value.join(',')
		};
	};
	// 获取活动数据
	const handleGetQueryOrderData = () => {
		let couponIds : string[] = [];
		if (couponId.value) {
			couponIds = couponId.value.split(',');
		}
		if (couponShareId) couponIds.push(couponShareId);
		const params = {
			data: preQueryData,
			// deductionStrategy: getDeductionStrategy(),
			couponId: couponIds.length ? couponIds.join(',') : couponId.value,
			// 优惠券码
			couponShareCode: couponShareCode.value,
			...getGiveStrategy()
		};
		if (!params.data) return;
		loading.value = true;
		activityV2(params)
			.then((res) => {
				isFirstCouponShare = false;

				info.value = res.data.order;
				const goodsType : number[] = [];
				info.value.orderVos.forEach((item) => {
					goodsType.push(...item.deputys.map((deputy) => deputy.type));

					// 获取所有商品的id集
					proIds.value = item.deputys.map((item) => item.commodityId).join(',');
				});
				// 1 实物 2虚拟物品
				isVirtualGoods.value = goodsType.includes(2);
				paltFormCoupon.value = res.data.coupon || [];
				deductionList.value = (res.data.deductionList as deductionAccountItem[]) || [];
				deductionModeId.value = deductionList.value.filter((item) => item.check).map((item) => item.strategy);
				giveList.value = (res.data.giveList as deductionAccountItem[]) || [];
				giveModeId.value = giveList.value?.[0]?.check ? [giveList.value?.[0]?.strategy] : [];
				if (paltFormCoupon.value && paltFormCoupon.value.length) showCoupon.value = true;
				const deduction = res.data.deduction;
				if (deduction) {
					deductionOpen.value = deduction.deductionOpen;
					deductionMode.value = deduction.deductionMode;
					deductionType.value = deduction.deductionType;
				}
				handleCalcDeduction();
			})
			.finally(() => {
				loading.value = false;
			});
	};

	const handleCalcDeduction = (obj ?: DeductionStrategy[], isOpen ?: number) => {
		const strategyMap : Record<string, string> = {};
		info.value.orderVos.forEach((vos) => {
			vos.deputys.forEach((deputy) => {
				// 判断是否是当前操作的商品
				const strategy : string[] = [];
				if (deputy.commoditySpecId === commoditySpecId.value && obj) {
					if (isOpen) {
						obj?.forEach((item) => {
							if (item.check) {
								strategy.push(item.strategy);
							}
						});
					}
					strategyMap[deputy.commoditySpecId] = strategy.join(',');
				} else {
					deputy?.params?.deductionStrategy?.forEach((item) => {
						if (item.check) {
							strategy.push(item.strategy);
						}
						strategyMap[deputy.commoditySpecId] = strategy.join(',');
					});
				}
			});
		});
		selectDeductionStrategy = strategyMap;
	};
	const handleChangeSelect = (obj : DeductionStrategy[], isOpen : number) => {
		discountPopShow.value = false;

		handleCalcDeduction(obj, isOpen);
		handleGetQueryOrderData();
	};
	const handleTapDiscount = (data : OrderGoods['deputys'][0], event : { currentTarget : { dataset : { url : OrderGoods['deputys'][0] } } }) => {
		// #ifdef MP-WEIXIN
		data = event.currentTarget.dataset.url;
		// #endif
		deductionStrategy.value = data.params ? data.params.deductionStrategy : [];
		selectedCommodityUrl.value = data.commodityUrl;
		discountPopShow.value = true;
		commoditySpecId.value = data.commoditySpecId;
		deputyMoneyDeduction.value = data.deputyMoneyDeduction;
	};
	// 更改优惠券选择
	const changeCouponStatus = (list : OrderCouponsItem[]) => {
		let couponIds : string[] = [];
		if (isPlat.value) {
			list.some((item) => {
				if (item.check) {
					couponIds.push(item.id);
					return true;
				}
			});
		} else {
			paltFormCoupon.value.some((item) => {
				if (item.check) {
					couponIds.push(item.id);
					return true;
				}
			});
		}
		info.value.orderVos.forEach((vos) => {
			if (vos.storeId === storeId.value) {
				list.some((item) => {
					if (item.check) {
						couponIds.push(item.id);
						return true;
					}
				});
			} else {
				vos.params?.coupon?.couponList.some((item) => {
					if (item.check) {
						couponIds.push(item.id);
						return true;
					}
				});
			}
		});
		couponId.value = couponIds.length ? couponIds.join(',') : '';
		handleGetQueryOrderData();
	};

	let deputys : {
		buys : { qty : string; sku : string }[];
	} = props.buys
			? JSON.parse(props.buys)
			: {
				buys: []
			};
	const getData = async () => {
		try {
			let params = {
				...pageParams,
				receivedId: address.value?.id,
				receivingType: receivingType.value,
				couponShareCode: couponShareCode.value
			};
			let res : any;
			loading.value = true;
			res = await behalfPaymentPre({ orderId: orderId.value })
			orderInfoVo.value = res.data.orderInfoVo
			if (orderInfoVo.value.invalidTime) {
				countDown()
			}

			loading.value = false;

			const _data = JSON.parse(JSON.stringify(res.data))
			delete _data.orderInfoVo
			preQueryData = JSON.stringify(_data)
			if (receivingType.value === 2) {
				receivingIds.value = [];
				getUserLocation().finally(() => {
					res?.orderVos?.forEach((item) => {
						getDeliveryPlaceList({
							storeId: item.storeId,
							location: longitude.value ? `${longitude.value},${latitude.value}` : ''
						}).then((_res) => {
							let params = {
								storeId: item.storeId,
								storeAddress: _res.data[0]
							};
							receivingIds.value.push(params);
						});
					});
				});
			}
			// receivingType 订单收货方式 ：1快递 2自提 3-闪送 4-核销 5-配送 pay接口
			const deliveryModes = res.deliveryModes;
			if (deliveryModes) {
				const arr : (typeof deliveryTabList)['value'] = [];
				if (deliveryModes.includes('3')) {
					arr.push({
						name: ctx.$t('classify.闪送'),
						value: 3
					});
				}
				if (deliveryModes.includes('6')) {
					arr.push({
						name: ctx.$t('classify.配送'),
						value: 5
					});
				}
				if (deliveryModes.includes('2')) {
					arr.push({
						name: ctx.$t('classify.快递'),
						value: 1
					});
				}
				if (deliveryModes.includes('5')) {
					arr.push({
						name: ctx.$t('classify.自提'),
						value: 2
					});
				}
				deliveryTabList.value = arr;
			}
		} catch (e) {
			loading.value = false;
		}

		// 优惠券码 如果存在优惠券码，先领券,再通过券码获取优惠券id，这个优惠券id要和平台券和商家券一起传给后端
		const couponShare = uni.getStorageSync('couponShare');
		if (couponShare) {
			const _couponShareCode = couponShare.couponShareCode;
			if (_couponShareCode) {
				const receiveCouponResult = await receiveSecurities(_couponShareCode);
				if (receiveCouponResult.code !== 200) {
					uni.removeStorageSync('couponShare');
					couponShareCode.value = '';
				}
				const result = await getCouponByShare({ couponShareCode: _couponShareCode });
				if (result.code == 200 && result.data) {
					couponShareId = result.data;
				}
				isFirstCouponShare = true;
				couponShareCode.value = _couponShareCode;
			}
		}
		handleGetQueryOrderData();
	};
	const payListRef = ref<PayListInstance>();
	const buy = throttle(function () {
		if (isVirtualGoods.value && !contactPhone.value) {
			ctx.$toastApp(ctx.$t('tools.qsrlxfs'));
			return;
		}
		if ([1, 3, 5].includes(receivingType.value) && !address.value?.id) {
			ctx.$toastApp(ctx.$t('classify.请先添加收货地址再支付'));
			return;
		}
		if (receivingType.value === 2) {
			let flag = false;
			receivingIds.value.some((item) => {
				if (item.predictTime && !item.storeAddress) {
					flag = true;
					return true;
				}
			});
			if (flag) {
				ctx.$toastApp(ctx.$t('classify.请先选择自提点'));
				return;
			}
		}
		// 闪送或者配送
		if ([3, 5].includes(receivingType.value)) {
			if (!deliveryTimes.value || !deliveryTimes.value.length) {
				if (receivingType.value === 3) {
					ctx.$toastApp(ctx.$t('classify.当前位置不支持闪送'));
				} else {
					ctx.$toastApp(ctx.$t('classify.当前位置不支持配送'));
				}
				return;
			} else if (!deliveryTimes.value[0].selectTime) {
				ctx.$toastApp(ctx.$t('classify.请选择预计送达时间'));
				return;
			}
			// 判断是否达到起送价 orderStartPrice
			let flag = info.value.orderVos.some((item) => {
				if (item.fig) {
					const fig = JSON.parse(item.fig);
					if (item.orderMoney < fig.orderStartPrice) {
						ctx.$toastApp(ctx.$t('classify.订单未达起送价'));
						return true;
					}
				} else {
					if (receivingType.value === 3) {
						ctx.$toastApp(ctx.$t('classify.当前位置不支持闪送'));
					} else {
						ctx.$toastApp(ctx.$t('classify.当前位置不支持配送'));
					}
					return true;
				}
			});
			if (!flag) {
				flag = info.value.orderVos.every((item) => !getCanList(item).length);
			}

			if (flag) return;
		}
		if (!payListRef.value?.payItem) {
			ctx.$toastApp(ctx.$t('nearby.请选择支付方式'));
			return;
		}

		if (info.value.payMoney) {
			if (payListRef.value.payItem.type === 'SYS') {
				show.value = true;
			} else {
				pay(payListRef.value.payItem.id, undefined, payListRef.value.payItem.type);
			}
		} else {
			// 如果支付金额为0，默认取第一个支付方式，默认支付密码为sanxinjava
			//  如果有余额账号默认余额，没有则取第一个
			let arr = payListRef.value?.payMode?.filter((item) => item.isDefault === 'Y');
			if (!arr || !arr.length) {
				arr = payListRef.value?.payMode;
			}
			if (arr && arr.length) {
				const item = arr[0];
				pay(item.id, 'sanxinjava', PayType.SYS);
			} else {
				ctx.$toastApp(ctx.$t('order.平台暂未开放支付'));
			}
		}
	}, 1000);

	const passwordPopupRef = ref<PasswordPopupInstance>();
	const passwordPay = (password : string) => {
		passwordPopupRef.value?.reset();
		show.value = false;
		pay(payListRef.value.payItem.id, password, payListRef.value.payItem.type);
	};
	// 支付
	const pay = throttle(async function (payId : number, payword : string | undefined = undefined, payType : PayType, bankId ?: number) {
		let couponId = [];
		if (couponShareId) couponId.push(couponShareId);
		if (paltFormCoupon.value.length) {
			paltFormCoupon.value.some((item) => {
				if (item.check) {
					couponId.push(item.id);
					return true;
				}
			});
		}
		info.value.orderVos.forEach((item) => {
			if (item.params && item.params.coupon && item.params.coupon.couponList.length) {
				item.params.coupon.couponList.some((list) => {
					if (list.check) {
						couponId.push(list.id);
						return true;
					}
				});
			}
		});
		// 自提
		const _receivingIds =
			receivingType.value === 2
				? receivingIds.value
					.map((item) => {
						if (item.storeAddress) {
							return {
								receivingId: item.storeAddress.id,
								storeId: item.storeId,
								predictTime: item.predictTime
							};
						}
						return null;
					})
					.filter((item) => item)
				: [];

		const _couponIds = new Set(couponId);
		const _remarks : { storeId : string; remark : string }[] = [];
		if (remarks.value) {
			Object.keys(remarks.value).forEach((item) => {
				_remarks.push({
					storeId: item,
					remark: remarks.value[item]
				});
			});
		}
		let params : PurchaseGoodsParams = {
			...pageParams,
			receivingId: storeAddress.value?.id,
			couponId: Array.from(_couponIds).join(','),
			// 订单类型：1快递 2自提 3-闪送 4-核销 5-配送
			receivingType: receivingType.value,
			// 优惠券码
			couponShareCode: couponShareCode.value,
			// 虚拟商品需要填写联系方式
			// virtuallyProPhone: contactPhone.value,
			// 闪送或者配送
			deliveryTimes: [3, 5].includes(receivingType.value) ? JSON.stringify(deliveryTimes.value) : '',
			receivingIds: _receivingIds.length ? JSON.stringify(_receivingIds) : '',
			remarks: _remarks.length ? JSON.stringify(_remarks) : '',
			deductionStrategy: props.type === '3' ? '' : getDeductionStrategy(),
			fromType: getApp<UniGlobalData>().globalData?.payFromType,
			receivedId: address.value?.id,
			payId,
			payword
		};


		let requireOrder = false;
		// #ifdef MP-WEIXIN
		if (props.isTrace) {
			let traceRes = await checkBeforeAddOrder();
			if (traceRes.code === 200) {
				params['traceId'] = traceRes.traceId;
				requireOrder = traceRes.requireOrder === 1;
			}
		}
		// #endif
		if (
			!bankId &&
			checkCardPay(payType, (cardId : number) => {
				pay(payId, payword, payType, cardId);
			})
		) {
			return;
		}
		uni.hideLoading();
		if (payType === PayType.DFK) {
			payLoading.value = false;
			// 如果是代付，则保存订单数据
			const orderParams = {
				data: params,
				type: props.type,
				isTrace: props.isTrace,
				requireOrder,
				payType,
				payResultApi: getPayResult
			}
			uni.setStorageSync('orderParams', JSON.stringify(orderParams))
			uni.navigateTo({
				url: '/pages/systemPay/proxyOrder/order?money=' + info.value.payMoney
			})
			return
		}
		let res : any;

		res = await behalfPayment({
			...params,
			...optParams.value,
			payOrderId: orderId.value,
			qty: props.qty || '',
			skuId: props.skuId || '',
			bankId
		});
		payLoading.value = false;

		const payStatus = await systemPay({
			payType,
			resolveData: res,
			api: getPayResult,
			storageKey: 'payOrderId',
			payUrl: res.data,
			payParams: res.data,
			successUrl: (id : string) => `order/success?type=4&id=${id}`,
			errorUrl: (msg : string) => `order/error?msg=${msg}`,
			orderUrl: 'order/index?type=1',
			isTrace: !!props.isTrace,
			requireOrder,
			payMoney: info.value.payMoney
		});
		if (typeof payStatus === 'boolean') {
			return;
		}
		if (props.type === '2') {
			getCart();
		}
		uni.removeStorageSync('couponShare');

	}, 1500);

	// #ifdef MP-WEIXIN
	const checkBeforeAddOrder = () : Promise<{
		traceId : string;
		requireOrder : number;
		code : number;
	}> => {
		return new Promise((resolve, reject) => {
			wx.checkBeforeAddOrder({
				success: (res) => {
					resolve({
						traceId: res.data.traceId,
						requireOrder: res.data.requireOrder,
						code: 200
					});
				},
				fail: (err : any) => {
					reject({
						code: 500
					});
					console.log(err);
				}
			});
		});
	};
	// #endif
	let isLoad = true;
	const orderId = ref()
	const optParams = ref()
	onLoad((opt) => {
		optParams.value = opt
		orderId.value = opt.id
		getAddressList()
			.then((res) => {
				if (res.data.length) {
					if (props.aId) {
						address.value = res.data.find((item) => `${item.id}` == props.aId);
					}
					if (!address.value) {
						address.value = res.data.find((item) => item.isDefaul === 1);
					}
				} else {
					showAddrPop.value = true;
				}
			})
			.finally(() => {
				getData();
			});
		// #ifdef HTML5 || PREVIEW
		getH5PayResult('order/success', 'payOrderId', getPayResult);
		// #endif
	});
	onShow(() => {
		if (isLoad) {
			isLoad = false;
		} else {
			if (!address.value) {
				getAddressList()
					.then((res) => {
						if (res.data.length) {
							address.value = res.data.find((item) => item.isDefaul === 1) || res.data[0];
						} else {
							showAddrPop.value = true;
						}
					})
					.finally(() => {
						getData();
					});
			}
		}
		storeAddress.value = uni.getStorageSync('storeAddressInfo') || undefined;
		deliveryTimes.value = uni.getStorageSync('deliveryTimes') || [];
		remarks.value = uni.getStorageSync('orderRemarks') || {};
	});
</script>

<style lang="scss" scoped>
	::v-deep {

		.coupon-share-box .uni-input-input,
		.custom-order-list .uni-input-input {
			text-align: right;
		}
	}

	.fixed-button {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 112rpx;
		padding: 0 28rpx;
		z-index: 1;

		button {
			width: 240rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			margin: 0;
		}
	}

	.placeholder-class {
		text-align: right;
	}

	.preview-order-mode {
		padding: 20rpx 32rpx;
		position: relative;

		&__mask {
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
			z-index: 1;
		}
	}

	.preview-proxy-order {
		width: 100vw;

		&__bg {
			width: 100vw;
			height: 292rpx;
			background: #4B68E3;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 1;
		}

		&__box {
			position: relative;
			z-index: 2
		}

		&__top {
			height: 162rpx
		}

		&__content {
			padding: 28rpx 20rpx;
		}

		&__line {
			height: 1rpx;
			background: #EFEFEF;
		}

		&__countdown {
			width: 36rpx;
			height: 36rpx;
			background: #4B68E3;
			border-radius: 4rpx;
		}
	}

	.img-80 {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}
</style>